package cn.platform.controller;

import cn.platform.entity.StuRecord;
import cn.platform.request.StuRecord.StuRecordQueryDTO;
import cn.platform.request.StuRecord.StuRecordUpdateDTO;
import cn.platform.response.PageResult;
import cn.platform.response.Result;
import cn.platform.response.StuRecordVO;
import cn.platform.service.StuRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/grade") // 成绩相关接口路径
public class GradeController {
    @Autowired
    private StuRecordService stuRecordService;

    // 新增：获取学生列表接口
    @GetMapping("/student")
    public Result getStudents(@RequestParam(required = false) String name) {
        return Result.success(stuRecordService.getStudents(name));
    }

    // 新增：获取老师列表接口
    @GetMapping("/teacher")
    public Result getTeachers(@RequestParam(required = false) String name) {
        return Result.success(stuRecordService.getTeachers(name));
    }


    /**
     * 分页条件查询
     * @param queryDTO
     * @return
     */
    @GetMapping
    public Result page(StuRecordQueryDTO queryDTO) {
        // 移除强制设置type为"成绩"的逻辑，允许前端传递任意类型
        queryDTO.setType("成绩");
        PageResult<StuRecordVO> pageResult = stuRecordService.page(queryDTO);
        return Result.success(pageResult);
    }


    @GetMapping("/{id}")
    public Result detail(@PathVariable Integer id) {
        log.info("查看学生成绩详情");
        StuRecordVO stuRecordVO = stuRecordService.detail(id);
        return Result.success(stuRecordVO);
    }

    @PostMapping
    public Result save(@RequestBody StuRecord stuRecord) {
        log.info("新增学生成绩");
        stuRecord.setType("成绩");
        //新增的
        if(stuRecord.getPubTime() == null) {
            stuRecord.setPubTime(LocalDateTime.now());
        }
        stuRecord.setUpdateTime(LocalDateTime.now());

        stuRecordService.save(stuRecord);

        return Result.success();
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable String id, @RequestBody StuRecordUpdateDTO stuRecordUpdateDTO ){
        log.info("更新学生成绩 ID {}: {}", id, stuRecordUpdateDTO);
        stuRecordUpdateDTO.setId(id);
        stuRecordService.update(stuRecordUpdateDTO);
        return Result.success();
    }


    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("删除学生成绩，ID: {}", id);
        stuRecordService.delete(id);
        return Result.success();
    }

    @PostMapping("/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        log.info("批量删除学生成绩，ID列表: {}", ids);
        stuRecordService.deleteBatch(ids);
        return Result.success();
    }
}